<template>
    <div class="login-container">
        <div class="login-box">
            <div class="login-title">
                <i class="fas fa-paw"></i>
                流浪动物救助平台
            </div>

            <!-- 登录表单 -->
            <el-form v-if="activeTab === 'login'" ref="loginFormRef" :model="loginForm" :rules="loginRules"
                label-width="0" class="login-form">
                <el-form-item prop="username">
                    <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="el-icon-user" />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="loginForm.password" type="password" placeholder="密码" prefix-icon="el-icon-lock"
                        show-password />
                </el-form-item>
                <el-form-item>
                    <el-radio-group v-model="loginForm.role" class="role-select">
                        <el-radio label="user">用户登录</el-radio>
                        <el-radio label="admin">管理员登录</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="login-button" :loading="loading"
                        @click="handleLogin">登录</el-button>
                </el-form-item>
            </el-form>

            <!-- 注册表单 -->
            <el-form v-else ref="registerFormRef" :model="registerForm" :rules="registerRules" label-width="0"
                class="login-form">
                <el-form-item prop="avatar" class="avatar-upload">
                    <el-upload class="avatar-uploader" action="/api/Userfile/upload" :show-file-list="false"
                        :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
                        <img v-if="registerForm.avatar" :src="`/api/Userfile/${registerForm.avatar}`" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item prop="name">
                    <el-input v-model="registerForm.name" placeholder="请输入姓名" prefix-icon="el-icon-user" />
                </el-form-item>
                <el-form-item prop="username">
                    <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user" />
                </el-form-item>
                <el-form-item prop="phone_number">
                    <el-input v-model="registerForm.phone_number" placeholder="请输入手机号" prefix-icon="el-icon-phone" />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input type="password" v-model="registerForm.password" placeholder="请输入密码"
                        prefix-icon="el-icon-lock" show-password />
                </el-form-item>
                <el-form-item prop="confirmPassword">
                    <el-input type="password" v-model="registerForm.confirmPassword" placeholder="请确认密码"
                        prefix-icon="el-icon-lock" show-password />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="login-button" @click="handleRegister">注册</el-button>
                </el-form-item>
            </el-form>

            <div class="login-options">
                <el-button type="text" @click="router.push('/')">返回首页</el-button>
                <el-button type="text" @click="activeTab = activeTab === 'login' ? 'register' : 'login'">
                    {{ activeTab === 'register' ? '返回登录' : '注册账号' }}
                </el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const router = useRouter()
const activeTab = ref('login')

const loginForm = ref({
    username: '',
    password: '',
    role: 'user'
})

const loginRules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    role: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

const registerForm = ref({
    avatar: '',
    name: '',
    username: '',
    phone_number: '',
    password: '',
    confirmPassword: '',
    role: 'user'
})

const validateConfirmPassword = (rule, value, callback) => {
    if (value !== registerForm.value.password) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

const validatePhoneNumber = (rule, value, callback) => {
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!value) {
        callback(new Error('请输入手机号'))
    } else if (!phoneRegex.test(value)) {
        callback(new Error('请输入正确的手机号'))
    } else {
        callback()
    }
}

const registerRules = {
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度应在2-20个字符之间', trigger: 'blur' }
    ],
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
    ],
    phone_number: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: validatePhoneNumber, trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' }
    ]
}

const loading = ref(false)

const handleLogin = async () => {
    loading.value = true
    try {
        const response = await request.post('/auth/login', loginForm.value)
        const { data } = response
        localStorage.setItem('userInfo', JSON.stringify(data))
        
        if (['admin'].includes(data.role)) {
            router.push('/admin')
        } else {
            router.push('/')
        }
        
        ElMessage({
            message: '登录成功！',
            type: 'success',
            duration: 2000
        })
    } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('登录失败，请检查用户名和密码')
    } finally {
        loading.value = false
    }
}

const handleRegister = async () => {
    try {
        const response = await request.post('/auth/userregister', registerForm.value)
        
        ElMessage({
            message: '注册成功！',
            type: 'success',
            duration: 2000
        })

        activeTab.value = 'login'
        
        // 清空表单
        registerForm.value = {
            avatar: '',
            name: '',
            username: '',
            phone_number: '',
            password: '',
            confirmPassword: '',
            role: 'user'
        }
    } catch (error) {
        console.error('注册失败:', error)
        ElMessage.error('注册失败，请检查输入信息')
    }
}

const beforeAvatarUpload = (file) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
    }
    return isJPG && isLt2M
}

const handleAvatarSuccess = (response) => {
    if (response.code === 200) {
        registerForm.value.avatar = response.data
        ElMessage.success('上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}
</script>

<style scoped>
.login-container {
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, #1e90ff 0%, #70a1ff 100%);
    position: relative;
    overflow: hidden;
}

.login-container::before {
    content: '';
    position: absolute;
    width: 200%;
    height: 200%;
    top: -50%;
    left: -50%;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
    animation: rotate 30s linear infinite;
}

@keyframes rotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

.login-box {
    width: 420px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 15px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    transform: translateY(0);
    transition: all 0.3s ease;
    position: relative;
    z-index: 1;
}

.login-box:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
}

.login-title {
    text-align: center;
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 35px;
    color: #2c3e50;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
}

.login-title i {
    font-size: 32px;
    color: #409EFF;
}

.login-form {
    margin-bottom: 25px;
}

.login-form :deep(.el-input__inner) {
    height: 45px;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.login-form :deep(.el-input__inner:focus) {
    border-color: #409EFF;
}

.role-select {
    width: 100%;
    display: flex;
    justify-content: center;
    margin: 10px 0 25px;
}

.login-button {
    width: 100%;
    height: 45px;
    font-size: 16px;
    border-radius: 8px;
    background: linear-gradient(45deg, #409EFF, #70a1ff);
    border: none;
    transition: all 0.3s ease;
}

.login-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(64, 158, 255, 0.3);
}

.login-options {
    display: flex;
    justify-content: center;
    gap: 30px;
    margin-top: 20px;
}

.login-options :deep(.el-button) {
    font-size: 14px;
    padding: 0;
    transition: all 0.3s ease;
}

.login-options :deep(.el-button:hover) {
    color: #409EFF;
    transform: translateY(-2px);
}

.avatar-upload {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
}

.avatar-uploader:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
}

.avatar-tip {
    font-size: 12px;
    color: #909399;
    text-align: center;
    margin-top: 5px;
}
</style>